<?php
defined('IN_IA') or exit('Access Denied');

require_once 'defines.php';
require_once MODULE_FUNC.'functions.php';

class Asterye_waimaixia_plugin_gzhModuleProcessor extends WeModuleProcessor {
    private $isOk = false;

    private $obj;
    private $poster;
    private $member;

    public function respond(){
        global $_W;
		
        $uniacid = $_W['uniacid'];
        $message = $this->message;
        $msgtype = strtolower($message['msgtype']);
        $event   = strtolower($message['event']);
        $this->member  = checkMember($message['from']);
        $this->responseClear();

        $this->obj = $this;

		$settings = getConfig();

        // 关键字或者底部菜单
        if ($msgtype == 'text' || $event == 'click') {
            sendCustomNotice($this->message['from'], "");
			//检测用户是否在小程序注册
			//小程序用户注册
			if($settings['system_type'] == 1){
				$fans = pdo_get("mc_mapping_fans", array("uid" => intval($this->member['uid']),'uniacid' => intval($_W['uniacid'])));
				$fans_member = pdo_get("mc_members", array("uid" => intval($this->member['uid']),'uniacid' => intval($_W['uniacid'])));
				$user = pdo_get(MODULE_XCXNAME . "_user_u", array("unionid" => $fans['unionid'], "system_id" => $settings["system_id"]));
				$user_cz = pdo_get(MODULE_XCXNAME . "_user", array("unionid" => $fans['unionid'], "system_id" => $settings["system_id"]));
				if($user_cz){
					if(empty($user)){
						unset($user_cz["user_id"]);
					    pdo_insert(MODULE_XCXNAME . "_user_u", $user_cz);
					}else{
						if($fans['unionid']){
							pdo_update(MODULE_XCXNAME . "_user", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
							pdo_update(MODULE_XCXNAME . "_user_u", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
						}
					}
					
				}else{
					if(empty($user)){
						$last_user = pdo_fetchall("SELECT uid FROM ".tablename(MODULE_XCXNAME. "_user")." where uid > 0 and system_id = ".$settings['system_id']." order by uid desc limit 1");
						if(!$last_user){
							if(intval($settings['uid']) == 0){$settings['uid'] = 16800000;}
							$data['uid'] = $settings['uid'] + 1;
						}else{
							$data['uid'] = $last_user[0]['uid'] + 1;
						}
						$fans_invite = pdo_get("mc_mapping_fans", array("uid" => intval($poster_member_qr['uid']),'uniacid' => intval($_W['uniacid'])));
						$invite_user = pdo_get(MODULE_XCXNAME . "_user_u", array("unionid" => $fans_invite['unionid'], "system_id" => $settings['system_id']));
						if(!$invite_user){
							$parent_id = 0;
							$invite_uid = '0';
							$parent_unionid = 0;
							$invite_unionid = '0';
						}else{
							$parent_id = $invite_user['uid'];
							if(empty($invite_user['invite_uid'])){$invite_user['invite_uid'] = '0';}
							$invite_uid = $invite_user['invite_uid'].'_'.$invite_user['uid'];
							$parent_unionid = $invite_user['unionid'];
							if(empty($invite_user['invite_unionid'])){$invite_user['invite_unionid'] = '0';}
							$invite_unionid = $invite_user['invite_unionid'].'#'.$invite_user['unionid'];
						}
						$data["uniacid"] = $_W["uniacid"];
						$data["system_id"] = $settings['system_id'];
						$data["openid"] = $fans['openid'];
						$data["parent_id"] = $parent_id;
						$data["invite_uid"] = $invite_uid;
						$data["parent_unionid"] = $parent_unionid;
						$data["invite_unionid"] = $invite_unionid;
						$data["nickname"] = $fans['nickname'];
						$data["unionid"] = $fans['unionid'];
						$data["new"] = 1;
						$data["avatar"] = $fans_member["avatar"];
						$data["create_time"] = $_W["timestamp"];
						pdo_insert(MODULE_XCXNAME . "_user_u", $data);
						$user1 = pdo_get(MODULE_XCXNAME . "_user", array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
						if(!$user1){
							pdo_insert(MODULE_XCXNAME . "_user", $data);
						}
						if($invite_user){
							pdo_update(MODULE_XCXNAME . "_user_u", array('invite_sum +=' => 1), array("user_id" => $invite_user["user_id"]));
						}
					}else{//对于已经存在的用户，更新昵称头像
						if($fans['unionid']){
							pdo_update(MODULE_XCXNAME . "_user", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
							pdo_update(MODULE_XCXNAME . "_user_u", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
						}
						
					}
				}
			}
			//小程序用户注册
			//检测用户是否在小程序注册
            return $this->responseTextSend($this);
        }
    
        // 关注事件
        else if($msgtype == 'event') {
            if ($event == 'scan') { // 扫码关注
                return $this->responseScan($this);
            }
    
            else if ($event == 'subscribe') { // 新用户关注
                return $this->responseSubscribe($this);
            }
        }
    }
    
    // 关键字触发事件
    private function responseTextSend($obj){
        global $_W;


        if(!empty($obj->message['content']) || !empty($_SESSION['keyword_content']) ){

            if(!empty($_SESSION['keyword_content'])){
                $poster = pdo_fetch("select id from " . tablename(MODULE_PREFIX.'poster') . " where keyword='".trim($_SESSION['keyword_content'])."' and uniacid =:uniacid limit 1",array(':uniacid'=>intval($_W['uniacid'])));
            }else{
                $poster = pdo_fetch("select id from " . tablename(MODULE_PREFIX.'poster') . " where keyword='".trim($obj->message['content'])."' and uniacid =:uniacid limit 1",array(':uniacid'=>intval($_W['uniacid'])));
                if( empty($poster) ){
                    return $this->responseText($obj);
                }
            }

            if(!empty($poster)){
                $this->isOpenAuto($obj,$poster['id'],true);
            }else{

                // 获取关注情况内容
                $config = getConfig();
                if(!empty($config['getinfo_keyword']) && !empty($config['getinfo_desc'])){
                    if(!empty($this->member['uid'])){
                        $nums = pdo_fetchcolumn("select count(1) from ".tablename(MODULE_PREFIX."log")." where uniacid=:uniacid and from_uid=:from_uid ",array(':uniacid'=>$_W['uniacid'],':from_uid'=>$this->member['uid']));

                        $remark = $config['getinfo_desc'];
                        $remark = str_replace("[nums]", intval($nums), $remark);
                        sendCustomNotice($obj->message['from'], $remark);
                    }
                }

            }

            return $this->responseEmpty();

        }
    }
    
    
    private function responseText($obj,$flag = true){
        global $_W;
        
        // 缓冲一下
        sendCustomNotice($obj->message['from'], "");
        
        if ($this->inContext && empty($_SESSION['keyword_content'])) {
            
            $poster_member_qr = pdo_fetch("select id,posterid from ".tablename(MODULE_PREFIX."qr")." where uniacid = ".intval($_W['uniacid'])." and reccode = '".$obj->message['content']."' ");
            $qid = $poster_member_qr['id'];
            
            if(!empty($poster_member_qr['posterid'])){
                $poster_random = pdo_fetchcolumn("select random from ".tablename(MODULE_PREFIX.'poster')." where id = ".intval($poster_member_qr['posterid']));
            }
            
            $this->endContext();
            
            if(empty($qid)){
                return $this->respText('邀请码输入有误,请重新输入!');
            }
            
            $this->endContext();
            $this->responseSubscribe($obj,$qid);
            
            if(!empty($poster_random)){
                return $this->responseEmpty();
            }else{
                return $this->respText('邀请成功!');
            }
        }
        
        # 查找是否存在关键字
        $rid = pdo_fetchcolumn("select rid from " . tablename('rule_keyword') . " where uniacid=:uniacid and module=:module and content=:content  limit 1", array(
            ":uniacid" => $_W['uniacid'],
            ":module" => MODULE_NAME,
            ":content" => trim($obj->message['content']),
        ));
        
        if(!empty($rid)){
            // 是否存在海报邀请规则id
            $posterid = pdo_fetchcolumn("select name from " . tablename('rule') . " where id = " . intval($rid));
            
            if(floatval($posterid) > 0){ // 订阅号输入邀请码
                if (!$this->inContext) {
                    $this->beginContext();
                    return $this->respText('请输入邀请码:');
                }
            }
        }

        // 生成海报
        $resp = $_W['siteroot'] . 'app/index.php?i=' . intval($_W['uniacid']) . '&c=entry&m='.MODULE_NAME.'&do=index&op=build&timestamp=' . time();
        $result = chttp_request($resp, array(
            'openid' => $obj->message['from'],
            'content' => urlencode($obj->message['content'])
        ), array(), 4);

        if($flag){
            return $this->responseEmpty();
        }
    }
    
    /**
     * 第二次扫码关注
     * @param unknown $obj
     */
    private function responseScan($obj){
        global $_W;

        if( !empty( $obj->message['content'] ) ){
            $this->responseTextSend($obj);
        }
        
        $poster_member_qr = pdo_fetch("select uid,openid,posterid,scenestr from ".tablename(MODULE_PREFIX.'qr')." where scenestr = '".trim($obj->message['eventkey'])."' ");
        
        if(!empty($poster_member_qr)){
            if($poster_member_qr['uid'] == $obj->member['uid']){
                $poster = pdo_fetch("select minetext from ".tablename(MODULE_PREFIX."poster")." where id=:id ",array(':id'=>$poster_member_qr['posterid']));
                sendCustomNotice($obj->message['from'], empty($poster['minetext']) ? "您扫了自己!" : $poster['minetext'] );
                return $this->responseEmpty();
            }else{
                $from_uid = pdo_fetchcolumn("select from_uid from ".tablename(MODULE_PREFIX.'log')." where uid = ".intval($obj->member['uid']));
                if($from_uid){
                    $from_nickname = pdo_fetchcolumn("select nickname from ".tablename('mc_members')." where uid = ".intval($from_uid));
                    if(empty($from_nickname)){
                        $_nickname = $this->setMemberInfo($from_uid,$poster_member_qr['openid']);
                        if(empty($_nickname)){
                            sendCustomNotice($obj->message['from'], "您已关注我们啦!");
                        }else{
                            sendCustomNotice($obj->message['from'], "您已通过“".$_nickname."”关注我们啦!");
                        }
                    }else{
                        sendCustomNotice($obj->message['from'], "您已通过“".$from_nickname."”关注我们啦!");
                    }
                }else{
                    sendCustomNotice($obj->message['from'], "您已关注我们啦!");
                }
            }
            // 获取上级信息 并执行了是否自动生成海报
            $this->isOpenGetParentInfo($poster_member_qr['posterid']);
        }

        return $this->responseEmpty();
    }

    // 获得上级会员信息
    private function isOpenGetParentInfo($posterid = 0){
        global $_W;

        $obj    = $this->obj;
        $poster = $this->poster;
        $member = $this->member;

        $level = pdo_fetchcolumn("select level,level2_uid from ".tablename(MODULE_PREFIX."member")." where uniacid=:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$obj->member['openid']));
        
        if(empty($poster) && !empty($posterid)){
          $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX."poster")." where id=:id ",array(':id'=>$posterid));  
          $this->poster = $poster;
        }

        if(!empty($poster) && !empty($member)){

            if($poster['is_parent_info']){
                // 一级会员
                $parent1_uid = pdo_fetchcolumn("select level2_uid from ".tablename(MODULE_PREFIX."member")." where uniacid=:uniacid and level = 2 and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$this->member['openid']));
                
                if(!empty($parent1_uid)){
                    $parent1 = pdo_fetch("select realname,nickname,mobile from ".tablename("mc_members")." where uniacid=:uniacid and uid=:uid ",array(':uniacid'=>$_W['uniacid'],':uid'=>$parent1_uid));
                    $remark = $poster['parent_info'];
                    $remark = str_replace("[realname]", $parent1['realname'], $remark);
                    $remark = str_replace("[nickname]", $parent1['nickname'], $remark);
                    $remark = str_replace("[mobile]"  , $parent1['mobile'], $remark);
                    $remark = str_replace("[cur_time]", date('Y-m-d H:i:s',time()), $remark);
                    sendCustomNotice($obj->message['from'], $remark);
                }
            }

        }

        if( $level == 1 && empty($level['level2_uid']) ){
            $this->isOpenAuto($obj,$posterid,true);
        }else{
            $this->isOpenAuto($obj,$posterid,false);
        }
    }

    // 检测是否自动生成  flag 区别生成海报的条件
    private function isOpenAuto($obj,$posterid = 0,$flag = false){
        global $_W;
		$message = $this->message;
        $msgtype = strtolower($message['msgtype']);
        $event   = strtolower($message['event']);
        set_time_limit(60);
        @ini_set('memory_limit', '256M');

        // isopenauto,subaudio_url,keyword,sub_sendval,sub_sendurl
        $poster = $this->poster;
        if(empty($poster)){
            $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX."poster")." where id=:id ",array(':id'=>$posterid));
            $this->poster = $poster;
        }

        if(!empty($poster)){

            // 自动生成
            if(!empty($poster['isopenauto'])){
                
                // 主动发送语音
                if(!empty($poster['subaudio_url'])){
                    sendVoice($obj->message['from'],$poster['subaudio_url']);
                }

				//如果是关键字或点击菜单触发
				if ($msgtype == 'text' || $event == 'click') {
				}else{
                // 推送文本消息
					if(!empty($poster['sub_sendval'])){
						$remark = $poster['sub_sendval'];
						$remark = str_replace("[nickname]", $obj->member['nickname'], $remark);
						$remark = str_replace("[cur_time]", date('Y-m-d',time()), $remark);
						sendCustomNotice($obj->message['from'], $remark,$poster['sub_sendurl']);
					}
				}

                //主动触发海报
                if(!empty($poster['keyword'])){
                    $obj->message['content'] = $poster['keyword'];
                    $this->responseText($obj);
                }

                $this->responseEmpty();
            }

            // 默认生成
            else{
				// 主动发送语音
                if(!empty($poster['subaudio_url'])){
                    sendVoice($obj->message['from'],$poster['subaudio_url']);
                }
				
				//如果是关键字或点击菜单触发
				if ($msgtype == 'text' || $event == 'click') {
				}else{
					// 推送文本消息
					if(!empty($poster['sub_sendval'])){
						$remark = $poster['sub_sendval'];
						$remark = str_replace("[nickname]", $obj->member['nickname'], $remark);
						$remark = str_replace("[cur_time]", date('Y-m-d',time()), $remark);
						sendCustomNotice($obj->message['from'], $remark,$poster['sub_sendurl']);
					}
				}

                

                // 是否生成海报
                if($flag){
                    //主动触发海报
                    if(!empty($poster['keyword'])){
                        $obj->message['content'] = $poster['keyword'];
                        $this->responseText($obj,$flag);
                    }
                }

                $this->responseEmpty();
                
            }

        }
    }

    /**
     * 第一次扫码关注
     * @param unknown $obj
     * @param unknown $qid
     */
    private function responseSubscribe($obj,$qid = 0){
        global $_W;
        
        set_time_limit(50);
        @ini_set('memory_limit', '256M');

        if(empty($qid)){
            $eventkey = $obj->message['eventkey'];
            
            if(empty($eventkey)){
                $this->responseTextSend($obj);
                return $this->responseEmpty();
            }
            
            $eventkey = trim(str_replace('qrscene_','',$obj->message['eventkey']));
                
            $poster_member_qr = pdo_fetch("select id,posterid,uid,openid,nums,randomnum,finish_random_nums from ".tablename(MODULE_PREFIX.'qr')." where uniacid = ".intval($_W['uniacid'])." and scenestr = '".$eventkey."'");
            
            if(!empty($poster_member_qr)){
                $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX.'poster')." where id = ".intval($poster_member_qr['posterid']));
                $this->accountIn($obj, $poster);
                $this->responseText($obj,false);
            }else{
                $this->responseTextSend($obj);
                return $this->responseEmpty();
            }
        }else{
            $poster_member_qr = pdo_fetch("select id,posterid,uid,openid,nums,randomnum,finish_random_nums from ".tablename(MODULE_PREFIX.'qr')." where id = ".intval($qid));
            if(!empty($poster_member_qr)){
                $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX.'poster')." where id = ".intval($poster_member_qr['posterid']));
                $this->accountIn($obj, $poster);
            }
        }
        
        $poster_member = pdo_fetch("select uid,nickname,credit1,credit2 from ".tablename("mc_members")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($poster_member_qr['uid']));
        if(empty($poster_member['nickname'])){
            $poster_member['nickname'] = $this->setMemberInfo($poster_member_qr['uid'],$poster_member_qr['openid']);
        }
        
        $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX.'poster')." where id = ".intval($poster_member_qr['posterid']));


        // 自己扫
        if($poster_member_qr['uid'] == $obj->member['uid']){ 
            sendCustomNotice($obj->member['openid'], "您扫了自己的推广海报关注了我们!");
        }
        // 关注者扫
        else{ 
            $this->finishSubscribe($obj,$poster_member,$poster_member_qr,$poster);
        }
        
        $this->isOpenGetParentInfo($poster_member_qr['posterid']);
        
        return $this->responseEmpty();
    }
    
    /**
     * 扫码关注返回信息
     * @param unknown $obj
     * @param unknown $poster
     */
    private function accountIn($obj,$poster = array()){
        // 图文推送
        if(empty($poster['subresptype'])){
            if (! empty($poster['resptitle'])) {
                $news = array(
                    array(
                        'title' => $poster['resptitle'],
                        'description' => $poster['respdesc'],
                        'picurl' => tomedia($poster['respthumb']),
                        'url' => $poster['respurl']
                    )
                );
                return $obj->respNews($news);
            }
        }else{
            if (!empty($poster['subresp_keyword'])) {
                sendCustomNotice($obj->member['openid'], $poster['subresp_keyword']);
                return $this->respText($poster['subresp_keyword']);
            }
        }
    }
    
    /**
     * 完成邀请任务
     * @param unknown $obj
     * @param unknown $poster_member
     * @param unknown $poster_member_qr
     * @param unknown $poster
     */
    private function finishSubscribe($obj,$poster_member,$poster_member_qr,$poster){
        global $_W;
		$settings = getConfig();
		$xcxsettings = pdo_getcolumn('uni_account_modules', array('uniacid' => $settings['xcx_id'], 'module' => MODULE_XCXNAME), 'settings');
        $xcxsettings = iunserializer($xcxsettings);
        // 缓冲一下
        sendCustomNotice($obj->member['openid'], "");
        
        if(empty($obj->member['nickname'])){
            $obj->member['nickname'] = $this->setMemberInfo($obj->member['uid'],$obj->member['openid']);
        }
        
        $exit_log = pdo_fetchcolumn("select count(1) from ".tablename(MODULE_PREFIX."log")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($obj->member['uid']));
        
        if(empty($exit_log) && !empty($poster)){
            $poster_log_data = array(
                'uniacid'   => intval($_W['uniacid']),
                'posterid'  => $poster_member_qr['posterid'],
                'uid'       => intval($this->member['uid']),
                'from_uid'  => intval($poster_member_qr['uid']),
                'subcredit' => $poster['subcredit'],
                'reccredit' => $poster['reccredit'],
                'recmoney'  => $poster['recmoney'],
                'submoney'  => $poster['submoney'],
                'createtime'=> time()
            );
            pdo_insert(MODULE_PREFIX."log",$poster_log_data);
			//小程序用户注册
			if($settings['system_type'] == 1){
				$fans = pdo_get("mc_mapping_fans", array("uid" => intval($this->member['uid']),'uniacid' => intval($_W['uniacid'])));
				$fans_member = pdo_get("mc_members", array("uid" => intval($this->member['uid']),'uniacid' => intval($_W['uniacid'])));
				$user = pdo_get(MODULE_XCXNAME . "_user_u", array("unionid" => $fans['unionid'], "system_id" => $settings["system_id"]));
				$user_cz = pdo_get(MODULE_XCXNAME . "_user", array("unionid" => $fans['unionid'], "system_id" => $settings["system_id"]));
				if($user_cz){
					if(empty($user)){
						unset($user_cz["user_id"]);
					    pdo_insert(MODULE_XCXNAME . "_user_u", $user_cz);
					}else{
						if($fans['unionid']){
							pdo_update(MODULE_XCXNAME . "_user", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
							pdo_update(MODULE_XCXNAME . "_user_u", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
						}
					}
					
				}else{
					if(empty($user)){
						$last_user = pdo_fetchall("SELECT uid FROM ".tablename(MODULE_XCXNAME. "_user")." where uid > 0 and system_id = ".$settings['system_id']." order by uid desc limit 1");
						if(!$last_user){
							if(intval($settings['uid']) == 0){$settings['uid'] = 16800000;}
							$data['uid'] = $settings['uid'] + 1;
						}else{
							$data['uid'] = $last_user[0]['uid'] + 1;
						}
						$fans_invite = pdo_get("mc_mapping_fans", array("uid" => intval($poster_member_qr['uid']),'uniacid' => intval($_W['uniacid'])));
						$invite_user = pdo_get(MODULE_XCXNAME . "_user_u", array("unionid" => $fans_invite['unionid'], "system_id" => $settings['system_id']));
						if(!$invite_user){
							$parent_id = 0;
							$invite_uid = '0';
							$parent_unionid = 0;
							$invite_unionid = '0';
						}else{
							$parent_id = $invite_user['uid'];
							if(empty($invite_user['invite_uid'])){$invite_user['invite_uid'] = '0';}
							$invite_uid = $invite_user['invite_uid'].'_'.$invite_user['uid'];
							$parent_unionid = $invite_user['unionid'];
							if(empty($invite_user['invite_unionid'])){$invite_user['invite_unionid'] = '0';}
							$invite_unionid = $invite_user['invite_unionid'].'#'.$invite_user['unionid'];
						}
						$data["uniacid"] = $_W["uniacid"];
						$data["system_id"] = $settings['system_id'];
						$data["openid"] = $fans['openid'];
						$data["parent_id"] = $parent_id;
						$data["invite_uid"] = $invite_uid;
						$data["parent_unionid"] = $parent_unionid;
						$data["invite_unionid"] = $invite_unionid;
						$data["nickname"] = $fans['nickname'];
						$data["unionid"] = $fans['unionid'];
						$data["new"] = 1;
						$data["avatar"] = $fans_member["avatar"];
						$data["create_time"] = $_W["timestamp"];
						pdo_insert(MODULE_XCXNAME . "_user_u", $data);
						$user1 = pdo_get(MODULE_XCXNAME . "_user", array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
						if(!$user1){
							pdo_insert(MODULE_XCXNAME . "_user", $data);
						}
						if($invite_user){
							pdo_update(MODULE_XCXNAME . "_user_u", array('invite_sum +=' => 1), array("user_id" => $invite_user["user_id"]));
						}
					}else{//对于已经存在的用户，更新昵称头像
						if($fans['unionid']){
							pdo_update(MODULE_XCXNAME . "_user", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
							pdo_update(MODULE_XCXNAME . "_user_u", array('nickname' => $fans['nickname'] ,'avatar' => $fans_member['avatar']), array("unionid" => $fans['unionid']));
						}
						
					}
				}
			}
			//小程序用户注册

            // 自动分组
            if(intval($poster['is_groupid']) == 1){
                $fans = pdo_get("mc_mapping_fans",array('openid'=>$obj->member['openid']));
                $openid = $obj->member['openid'];

                $fanid = $fans['fanid'];
                $tags = array( $poster['groupid'] );

                $account_api = WeAccount::create();
                $result = $account_api->fansTagTagging($openid, $tags);

                if ( !is_error($result) ) {
                    pdo_delete('mc_fans_tag_mapping', array('fanid' => $fanid));
                    if (!empty($tags)) {
                        foreach ($tags as $tag) {
                            pdo_insert('mc_fans_tag_mapping', array('fanid' => $fanid, 'tagid' => $tag));
                        }
                        $tags = implode(',', $tags);
                    }
                    pdo_update('mc_mapping_fans', array('groupid' => $tags), array('fanid' => $fanid));
                }
                
                // pdo_update( "mc_mapping_fans" ,array('groupid'=>$poster['groupid']), array( 'uid'=> intval($obj->member['uid']) ));
            }

            if(intval($poster['isopen_level']) == 1){
                // 是否开启三级营销
                updateMemberLevel(intval($this->member['uid']),$poster);
            }else{
                // 更新AB统计
                up_level($this->member['uid'],$poster_member_qr['uid']);
            }
        
            // 系统总邀请关注人数
            $sysrandomnums = pdo_fetchcolumn("select sum(randomnum) from ".tablename(MODULE_PREFIX.'member')." where uniacid = ".intval($_W['uniacid']));
            
            if(!empty($poster_member_qr['uid'])){ // 推荐海报不为空
                
                if($poster['reccredit'] > 0){ // 邀请-奖励推荐人积分
                    setCredit($poster_member_qr['uid'],'credit1', intval($poster['reccredit']) , array($poster_member_qr['uid'],"邀请好友关注获取积分奖励！"));
                }

                if($poster['recmoney'] > 0){ // 邀请-推荐人奖励余额
					if($settings['system_type'] == 1){
						$fans = pdo_get("mc_mapping_fans", array("uid" => $poster_member_qr['uid']));
						if($fans['unionid']){
							pdo_update(MODULE_XCXNAME."_user_u", array('money +=' => $poster['recmoney']), array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
							$user = pdo_get(MODULE_XCXNAME."_user_u", array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
						   $result = pdo_insert(MODULE_XCXNAME."_user_logs_u", array("user_id" => $user['user_id'], "system_id" => $settings['system_id'], "num" => $poster['recmoney'], "create_time" => $_W["timestamp"], "reason" => '邀请奖励'));
						}
						//小程序奖励
					}else{
						setCredit($poster_member_qr['uid'],'credit2', floatval($poster['recmoney']), array($poster_member_qr['uid'],"邀请好友关注获取余额奖励！"));
					}
                    
                }

                // 推荐者邀请任务人数
                $myrandomnums = pdo_fetchcolumn("select count(1) from ".tablename(MODULE_PREFIX."log")." where uniacid=:uniacid and from_uid=:from_uid ",array(':uniacid'=>$_W['uniacid'],':from_uid'=>$poster_member_qr['uid']));
        
                $scantext   = $poster['scantext'];   //推荐者通知
                if(!empty($scantext)){
                    $scantext = str_replace("[nickname]", $obj->member['nickname'], $scantext);
                    $scantext = str_replace("[credit]", $poster['reccredit'] , $scantext);
                    $scantext = str_replace("[money]", $poster['recmoney'] , $scantext);
                    $scantext = str_replace("[sysrandomnums]", $sysrandomnums , $scantext);
                    $scantext = str_replace("[myrandomnums]", $myrandomnums , $scantext);
                    $scantext = str_replace("[nums]", intval($poster_member_qr['nums']) + 1 , $scantext);
                    $scantext = str_replace("[allcredit]", $poster_member['credit1'] , $scantext);
                    $scantext = str_replace("[allmoney]", $poster_member['credit2'] , $scantext);
                    $scantext = str_replace("[random]", intval($poster['random'] - ($poster_member_qr['randomnum'] + 1)) <= 0 ? 0 : intval($poster['random'] - ($poster_member_qr['randomnum'] + 1)) , $scantext);
        
                    // 关注推送
                    if(!empty($poster['templateid'])){
                        sendTplNotice($poster_member_qr['openid'], $poster['templateid'], postdata('','',$scantext));
                    }else{
                        sendCustomNotice($poster_member_qr['openid'], $scantext);
                    }
                }

                # 随机数触发活动
                $randomnum_flag = true;
                if(!empty($poster['random'])){
                    
                    $randomnum = intval($poster_member_qr['randomnum']) + 1;
                    $sum_randomnum = intval($poster_member_qr['finish_random_nums']);
                    
                    
                    if(intval($poster['limitrandom']) > intval($sum_randomnum) || empty($poster['limitrandom']) ){

                        # 关注进来推送消息
                        $scan_random_text = $poster['scan_random_text'];
                        if(intval($poster['random'] - ($poster_member_qr['randomnum'] + 1)) > 0){
                            if(!empty($scan_random_text)){
                                $scan_random_text = str_replace("[nickname]", $obj->member['nickname'], $scan_random_text);
                                $scan_random_text = str_replace("[credit]", $poster['reccredit'] , $scan_random_text);
                                $scan_random_text = str_replace("[money]", $poster['recmoney'] , $scan_random_text);
                                $scan_random_text = str_replace("[sysrandomnums]", $sysrandomnums , $scan_random_text);
                                $scan_random_text = str_replace("[myrandomnums]", $myrandomnums , $scan_random_text);
                                $scan_random_text = str_replace("[nums]", intval($poster_member_qr['nums']) + 1 , $scan_random_text);
                                $scan_random_text = str_replace("[allcredit]", $poster_member['credit1'] , $scan_random_text);
                                $scan_random_text = str_replace("[allmoney]", $poster_member['credit2'] , $scan_random_text);
                                $scan_random_text = str_replace("[random]", intval($poster['random'] - ($poster_member_qr['randomnum'] + 1)) <= 0 ? 0 : intval($poster['random'] - ($poster_member_qr['randomnum'] + 1)) , $scan_random_text);
                            
                                // 关注推送
                                if(!empty($poster['templateid'])){
                                    sendTplNotice($poster_member_qr['openid'], $poster['templateid'], postdata('','',$scan_random_text));
                                }else{
                                    sendCustomNotice($poster_member_qr['openid'], $scan_random_text);
                                }
                            }
                        }

                        // 
                        if($poster['limitrandom'] == $sum_randomnum && intval($poster['limitrandom']) != 0){
                            $randomnum_flag = false;
                        }
                    
                        // 只有一次
                        if(($poster['limitrandom'] == 1 || ($poster['limitrandom'] <= $sum_randomnum + 1 && $poster['limitrandom'] > 1)) && $randomnum >= $poster['random'] && $randomnum_flag){ // 限制完成次数
                            sendRandomNotice($poster_member_qr);
                            $randomnum_flag = false;
                        }
                    
                        // 不限次数
                        if(empty($poster['limitrandom']) && ($randomnum >= $poster['random']) ){
                            $randomnum_flag = true;
                        }

                        // 新一轮提醒
                        if($randomnum >= $poster['random'] && $randomnum_flag){
                            $randomnum = 0;
                            $randomnum_flag = true;

                            if(!empty($poster['next_active_text'])){
                                if(!empty($poster['templateid'])){
                                    sendTplNotice($poster_member_qr['openid'], $poster['templateid'], postdata('','',$poster['next_active_text']));
                                }else{
                                    sendCustomNotice($poster_member_qr['openid'],$poster['next_active_text']);
                                }
                            }

                            sendRandomNotice($poster_member_qr);
                        }
                        
                        if($randomnum_flag){
                            pdo_update(MODULE_PREFIX."qr",array('randomnum' => $randomnum),array('id'=>$poster_member_qr['id']));
                        }

                    }
                }
            }
        
            if(!empty($obj->member['uid'])){ // 关注着者提醒
                
                if($poster['subcredit'] > 0){
                    setCredit($obj->member['uid'],'credit1', intval($poster['subcredit']) , array($obj->member['uid'],"营销海报-关注获取积分奖励！"));
                }
                if($poster['submoney'] > 0){
                    setCredit($obj->member['uid'],'credit2', floatval($poster['submoney']), array($obj->member['uid'],"营销海报-关注获取余额奖励！"));
                }
            
                $subtext = $poster['subtext']; //关注者
                
                if(!empty($subtext)){
                    $cur_member = pdo_fetch("select credit1,credit2 from ".tablename("mc_members")." where uid = " . intval($obj->member['uid']));
                    
                    $subtext  = str_replace("[nickname]", $poster_member['nickname'], $subtext);
                    $subtext  = str_replace("[credit]", $poster['subcredit'] , $subtext);
                    $subtext  = str_replace("[money]", $poster['submoney'] , $subtext);
                    $scantext = str_replace("[sysrandomnums]", $sysrandomnums , $scantext);
                    $scantext = str_replace("[allcredit]", $cur_member['credit1'] , $subtext);
                    $scantext = str_replace("[allmoney]", $cur_member['credit2'] , $subtext);
                    
                    if(!empty($poster['templateid'])){
                        sendTplNotice($obj->member['openid'], $poster['templateid'], postdata('','',$subtext));
                    }else{
                        sendCustomNotice($obj->member['openid'], $subtext);
                    }
                }

            }

            pdo_update(MODULE_PREFIX."member"," scancodenum = scancodenum + 1 ",array('uid'=>$poster_member_qr['uid']));
            pdo_update(MODULE_PREFIX."qr"," nums = nums + 1 ",array('id'=>$poster_member_qr['id']));
        }else{
            return $this->responseEmpty();
        }
    }
    
    private function responseClear(){
        echo '';
        ob_clean();
        ob_start();
        echo '';
        ob_flush();
        ob_end_flush();
    }

    private function responseEmpty(){
        echo '';
        ob_clean();
        ob_start();
        echo '';
        ob_flush();
        ob_end_flush();
        exit(0);
    }
    
    private function responseDefault($obj){
        global $_W;
        return $obj->respText('感谢您的关注!');
    }
    
    /**
     * 深度捕获用户昵称
     * @param unknown $uid
     * @param unknown $openid
     * @return Ambigous <string, boolean>
     */
    private function setMemberInfo($uid,$openid){
        global $_W;
        $access_token = getAccount()->fetch_token();
        
        $fans = pdo_fetch("select nickname,tag from ".tablename("mc_mapping_fans")." where uniacid =:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$openid));
        if(!empty($fans['tag'])){
            $tag = unserialize(base64_decode($fans['tag']));
            $member = array(
                'uid' => $member['uid'],
                'nickname' => $tag['nickname'],
                'avatar' => $tag['headimgurl'],
                'gender' => $tag['sex'],
                'resideprovince' => $tag['province'],
                'residecity' => $tag['city'],
            );
            pdo_update("mc_members",$member,array('uid'=>$member['uid']));
            $_nickname = $tag['nickname'] ? $tag['nickname'] : $fans['nickname'];
        }else{

            $_nickname = pdo_fetchcolumn("select nickname from ".tablename('mc_mapping_fans')." where uniacid = '".intval($_W['uniacid'])."' and openid = '".$openid."' order by fanid desc limit 1 ");
            
            if(!empty($_nickname)){
                pdo_update("mc_members",array('nickname'=>$_nickname),array('uid'=>$uid));
            }else{
                $_nickname = pdo_fetchcolumn("select nickname from ".tablename('mc_members')." where uniacid = '".intval($_W['uniacid'])."' and uid = '".$uid."' order by uid desc limit 1 ");
                if(empty($_nickname)){
                    $result = ihttp_get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN");
                    if($result['status'] == 0){
                        $result = json_decode($result['content'],true);
                    }
                    
                    $_nickname = strval($result['nickname']);
                    if(!empty($uid)){
                        pdo_update("mc_mapping_fans",array('nickname'=>$_nickname),array('uid'=>$uid));
                        pdo_update("mc_members",array('nickname'=>$_nickname,'avatar'=>$result['headimgurl']),array('uid'=>$uid));
                    }
                }
            }
            
            if(!empty($_nickname)){
                $is_poster_member = pdo_fetchcolumn("SELECT count(*) FROM ".tablename(MODULE_PREFIX."member")." WHERE uid = $uid ");
                if(empty($is_poster_member)){
                    $members = array(
                        'uniacid' => $_W['uniacid'],
                        'uid' => $uid,
                        'openid' => $openid,
                        'nickname' => strval($_nickname),
                        'scancodenum' => 0,
                        'createtime' => TIMESTAMP
                    );
                    pdo_insert(MODULE_PREFIX."member",$members);
                }else{
                    pdo_update(MODULE_PREFIX."member",array('nickname'=>$_nickname),array('uid'=>$uid));
                }
            }
            
        }

        return $_nickname;
    }
}